package com.yicong.ants.scenic

import android.Manifest
import android.content.Context
import androidx.activity.result.ActivityResultLauncher
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.Utils
import java.lang.ref.WeakReference


object LocationUtil {
    private lateinit var mLocationClient: WeakReference<AMapLocationClient>
    var aMapLocation: AMapLocation? = null
    fun startLocateOnce(context:Context, lifecycleOwner: LifecycleOwner, callback: Callback) {
        //初始化client

        AMapLocationClient.updatePrivacyShow(context, true, true)
        AMapLocationClient.updatePrivacyAgree(context, true)
        if (lifecycleOwner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
            return
        }
        mLocationClient = WeakReference(AMapLocationClient(Utils.getApp()))
        if (PermissionUtils.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            innerStartLocate(lifecycleOwner, callback)
        } else {
            callback.onRequestPermission()
        }
    }

    private fun innerStartLocate(
        lifecycleOwner: LifecycleOwner,
        callback: Callback
    ) {
        mLocationClient.get()?.setLocationListener {
            if (lifecycleOwner.lifecycle.currentState == Lifecycle.State.DESTROYED) {
                return@setLocationListener
            }
            aMapLocation = it
            callback.onLocation(it)
        }
        mLocationClient.get()?.setLocationOption(AMapLocationClientOption().apply {
            locationPurpose = AMapLocationClientOption.AMapLocationPurpose.SignIn
            locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            isOnceLocation = true
            isOnceLocationLatest = true
        })
        mLocationClient.get()?.stopLocation()
        mLocationClient.get()?.startLocation()
    }

    fun requestPermission(locationPermissionLauncher: ActivityResultLauncher<String>) {
        locationPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
    }

    interface Callback {
        fun onRequestPermission()
        fun onLocation(location: AMapLocation)
    }
}